package 哈夫曼树;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;

public class HuffmanTree {
    static ArrayList<Node> list = new ArrayList<>();
    public static void main(String[] args) {
        int[] arr = {13,7,8,3,29,6,1};
        createHuffmanTree(arr);
        preSort();
    }

    // 创建哈夫曼树的方法
    public static void createHuffmanTree(int[] arr){
        // 遍历数组,将其放入list中
        for (int j : arr) {
            list.add(new Node(j));
        }
        while (list.size()> 1) {
            // 排序,从小到大
            Collections.sort(list);

            // 取出根节点权值最小的两颗二叉树
            Node left = list.get(0);
            Node right = list.get(1);

            // 构建一颗新的二叉树
            Node node = new Node(left.value+right.value);
            node.left = left;
            node.right = right;

            // 移除节点并添加节点
            list.remove(left);
            list.remove(right);
            list.add(node);
        }
    }

    public static void preSort(){
        Node root = list.get(0);
        if(root == null){
            System.out.println("二叉树为空");
            return;
        }else{
            root.preSort();
        }
    }
}


// 创建节点
class Node implements Comparable<Node>{
    int value;// 节点权值
    Node left;// 指向左子节点
    Node right;// 指向右子节点
    public Node(int no){
        this.value = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node node) {
        return this.value - node.value;
    }

    // 前序遍历
    public void preSort(){
        System.out.println(this);
        if(this.left != null){
            this.left.preSort();
        }

        if(this.right != null){
            this.right.preSort();
        }
    }
}